<template>
  <div class="app-container">
    <t-form
      :model="queryParams"
      ref="queryRef"
      layout="inline"
      v-show="showSearch"
      class="mb20"
    >
      <t-form-item label="部门名称" name="deptName">
        <t-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-select
          v-model="queryParams.status"
          placeholder="部门状态"
          clearable
          style="width: 200px"
        >
          <t-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </t-select>
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search" />
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh" />
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>

    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
          theme="primary"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
          >新增
          <template #icon> <t-icon name="add" /> </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button theme="default" @click="toggleExpandAll"
          >展开/折叠
          <template #icon>
            <t-icon name="unfold-less" />
          </template>
        </t-button>
      </t-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <t-enhanced-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :columns="columns"
      :tree="{ defaultExpandAll: isExpandAll }"
    >
      <template #status="{ row }">
        <dict-tag :options="sys_normal_disable" :value="row.status" />
      </template>
      <template #createTime="{ row }">
        <span>{{ parseTime(row.createTime) }}</span>
      </template>
      <template #action="{ row }">
        <t-button
          variant="text"
          theme="primary"
          @click="handleUpdate(row)"
          v-hasPermi="['system:dept:edit']"
          >修改
          <template #icon>
            <t-icon name="edit" />
          </template>
        </t-button>
        <t-button
          variant="text"
          theme="primary"
          @click="handleAdd(row)"
          v-hasPermi="['system:dept:add']"
          >新增
          <template #icon>
            <t-icon name="add" />
          </template>
        </t-button>
        <t-button
          v-if="row.parentId != 0"
          variant="text"
          theme="primary"
          @click="handleDelete(row)"
          v-hasPermi="['system:dept:remove']"
          >删除
          <template #icon>
            <t-icon name="delete" />
          </template>
        </t-button>
      </template>
    </t-enhanced-table>

    <!-- 添加或修改部门对话框 -->
    <t-dialog :title="title" v-model:visible="open" width="600px" attach="body">
      <t-form ref="deptRef" :data="form" :rules="rules" label-width="80px">
        <t-row>
          <t-col :span="12" v-if="form.parentId !== 0" class="mb10">
            <t-form-item label="上级部门" name="parentId">
              <t-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :tree-props="{
                  keys: {
                    label: 'deptName',
                    value: 'deptId',
                    children: 'children',
                  },
                }"
                placeholder="选择上级部门"
                check-strictly
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="部门名称" name="deptName">
              <t-input v-model="form.deptName" placeholder="请输入部门名称" />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="显示排序" name="orderNum">
              <t-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="负责人" name="leader">
              <t-input
                v-model="form.leader"
                placeholder="请输入负责人"
                :maxlength="20"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="联系电话" name="phone">
              <t-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                :maxlength="11"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="邮箱" name="email">
              <t-input
                v-model="form.email"
                placeholder="请输入邮箱"
                :maxlength="50"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb10">
            <t-form-item label="部门状态">
              <t-radio-group v-model="form.status">
                <t-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label"
                ></t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitForm">确 定</t-button>
          <t-button theme="default" @click="cancel">取 消</t-button>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const deptRef = ref(null);

const columns = ref([
  { colKey: "deptName", title: "部门名称", width: "260" },
  { colKey: "orderNum", title: "排序", width: "200" },
  { colKey: "status", title: "状态" },
  { colKey: "createTime", title: "创建时间" },
  { colKey: "action", title: "操作" },
]);

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined,
  },
  rules: {
    parentId: [
      { required: true, message: "上级部门不能为空", trigger: "blur" },
    ],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门列表 */
function getList() {
  loading.value = true;
  listDept(queryParams.value).then((response) => {
    deptList.value = proxy.handleTree(response.data, "deptId");
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0",
  };
  proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  listDept().then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  if (row != undefined) {
    form.value.parentId = row.deptId;
  }
  open.value = true;
  title.value = "添加部门";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  listDeptExcludeChild(row.deptId).then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改部门";
  });
}
/** 提交按钮 */
const submitForm = () => {
  deptRef.value.validate().then((valid) => {
    if (valid === true) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.deptName + '"的数据项?')
    .then(function () {
      return delDept(row.deptId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
